/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package UI;

import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.table.DefaultTableModel;
import modela2_practica1.Punto;
import modela2_practica1.graficarDatos;
import org.jfree.chart.ChartPanel;

/**
 *
 * @author Wicho
 */
public class frmSimulador extends javax.swing.JFrame {

    /**
     * Almacena la velociddad inicial en Y de la simulacion
     */
    private double velocidadInicial;
    /**
     * Almacena el tiempo que durara la simulacion
     */
    private double tiempoSimulacion;
    /**
     * Creates new form frmSimulador
     */
    
    java.util.LinkedList<Punto> coordenadas;
    
    private double b0;
    private double b1;
    
    private graficarDatos grafica1;
    private graficarDatos grafica2;
    
    public frmSimulador() {
        velocidadInicial = tiempoSimulacion = 0.0;
        initComponents();
        this.jTabbedPane1.setSelectedIndex(0);
        grafica1 = new modela2_practica1.graficarDatos("Caida libre");
        grafica2 = new modela2_practica1.graficarDatos("Modelo de regresion");
        this.generarChart1();
        this.generarChart2();
        
    }
    
    /**
     * Dado un instante de tiempo ,devuelve la coordenada en X según el modelo
     * @param tiempo
     * @return la coordenada en X para un instante dado
     */
    private double darCoordenadaX(double tiempo)
    {
        double coordenada = 3*tiempo;
        return coordenada;
    }
    
    /**
     * Dado un instante de tiempo ,devuelve la coordenada en Y según el modelo
     * @param tiempo
     * @return la coordenada en Y para un instante dado
     */
    private double darCoordenadaY(double tiempo)
    {
        double coordenada = ((this.velocidadInicial*tiempo)-(4.9*tiempo*tiempo))+100;
        return coordenada;
    }
    
    /**
     * Valida que los datos de entrada de la simulacion sean validos(numeros)
     * @return true si los datos son validos,false si no
     */
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jPanel5 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel6 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Iniciar Simulacion");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Velocidad Inicial");

        jLabel2.setText("Tiempo");

        jLabel3.setText("m/s");

        jLabel4.setText("s");

        jPanel3.setLayout(new java.awt.BorderLayout());

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(368, 368, 368)
                                .addComponent(jButton1))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(206, 206, 206)
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel3)
                                .addGap(71, 71, 71)
                                .addComponent(jLabel2)
                                .addGap(18, 18, 18)
                                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel4)))
                        .addGap(0, 280, Short.MAX_VALUE))
                    .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Simulador", jPanel1);

        jPanel2.setLayout(new java.awt.GridLayout(1, 2));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "X", "X"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel5Layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 344, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jPanel2.add(jPanel5);

        jPanel6.setLayout(new java.awt.BorderLayout());
        jPanel2.add(jPanel6);

        jTabbedPane1.addTab("Resultados", jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        
        boolean sonValidos = false;//indica si ambos numeros son validos,falso si no tienen formato numerico
        try
        {
            this.tiempoSimulacion = Double.parseDouble(this.jTextField2.getText());
            this.velocidadInicial = Double.parseDouble(this.jTextField1.getText());
            sonValidos = true;
        }
        catch(NumberFormatException err)
        {
            javax.swing.JOptionPane.showMessageDialog(this, "Verifique que los datos ingresados sean validos(numeros).");
            sonValidos = false;
        }
        
        if(!sonValidos) {
            return;
        }
        
         this.dibujar();
         this.calcularParametrosB();
         
         String modelo ="";
         
         if(b1<0)
             modelo ="Y = "+this.b0+" "+this.b1+"X";
         else if(b1==0)
             modelo = "Y = "+this.b0;
         else if(b1>0)
             modelo = "Y = "+this.b0+ " +"+this.b1+"X";
         this.jLabel5.setText("El modelo de regresión es:"+modelo);
         
         this.grafica2.agregarXY(0, this.obtenerYRegresion(0));
        for(Punto punto:this.coordenadas)
        {
            Object valores[] = new Object[2];
            valores[0] = punto.getX();
            valores[1] = punto.getY();
            ((DefaultTableModel)this.jTable1.getModel()).addRow(valores);
            
            this.grafica2.agregarXY((double)valores[0],this.obtenerYRegresion((double)valores[0]));
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    
    /**
     * Dibuja la trayectoria seguida en base a los datos ingresatos
     */
    private void dibujar()
    {
        
        long tiempoEjecucionMilisegundos = (long)this.tiempoSimulacion*1000;
        double tiempoCorriendo = 0;
        long iteracion = 0;
        this.coordenadas = new java.util.LinkedList<>();
        double coordenadaX;
        double coordenadaY;
        
        this.grafica1.resetearSerie();
        this.grafica2.resetearSerie();
        ((DefaultTableModel)this.jTable1.getModel()).setRowCount(0);
        long tiempoInicio = System.currentTimeMillis();
        
        long tiempoPrueba = System.currentTimeMillis();
        while(tiempoCorriendo<=tiempoEjecucionMilisegundos)
        {
            if(iteracion%10000000 == 0)//para que dibuje aproximadamente cada cuarto de segundo
            { 
                coordenadaX = this.darCoordenadaX(tiempoCorriendo/1000);
                coordenadaY = this.darCoordenadaY(tiempoCorriendo/1000);
                if(coordenadaY<0)
                {
                    //coordenadaY = 0;
                    javax.swing.JOptionPane.showMessageDialog(this,
                            "El objeto ha alcanzado el nivel del suelo en el tiempo:"+tiempoCorriendo/1000+" ,la simulacion se ha detenido faltando "+(this.tiempoSimulacion-tiempoCorriendo/1000)+" segundos");
                    this.coordenadas.add(new Punto(coordenadaX,coordenadaY));
                    //graficar ultimo punto
                    this.grafica1.agregarXY(coordenadaX, coordenadaY);
                    break;//salir del ciclo
                }
                this.coordenadas.add(new Punto(coordenadaX,coordenadaY));
                //graficar punto
                this.grafica1.agregarXY(coordenadaX, coordenadaY);
            }    
            tiempoCorriendo = System.currentTimeMillis()-tiempoInicio;
            iteracion++;
        }
        
        
        if(this.coordenadas.getLast().getY()>0)
            javax.swing.JOptionPane.showMessageDialog(null, "El objeto nunca toco el suelo,tiempo insuficiente para la simulacion.");
        
    }
    
    
    private double obtenerYRegresion(double x)
    {
        return this.b0+(this.b1*x);
    }
    private void generarChart1()
    {
        this.jPanel3.removeAll();
        ChartPanel panel =  grafica1.getGrafica("Caida libre","Desplazamiento", "Altura");
        this.jPanel3.add(panel,BorderLayout.CENTER);
        this.jPanel3.validate();
    }
    
    private void generarChart2()
    {
        this.jPanel6.removeAll();
        ChartPanel panel = grafica2.getGrafica("Modelo lineal", "X", "Y");
        this.jPanel6.add(panel,BorderLayout.CENTER);
        this.jPanel6.validate();
    }
    
    private double calcularPromedioDeX()
    {
        if(this.coordenadas == null)
            return -1;
        double promedio = 0;
        
        for(Punto punto:this.coordenadas)
        {
            promedio+=punto.getX();
        }
        
        promedio/=this.coordenadas.size();
        
        return promedio;
    }
    
    private double calcularPromedioDeY()
    {
        if(this.coordenadas == null)
            return -1;
        double promedio = 0;
        
        for(Punto punto:this.coordenadas)
        {
            promedio+=punto.getY();
        }
        
        promedio/=this.coordenadas.size();
        
        return promedio;
    }
    
    /**
     * el numerador para calcular b1
     * @return sumatoria((Xi-Xmedia)(Yi-Ymedia))
     */
    private double calcularSumatoriaDeDiferencias(double promedioX,double promedioY)
    {
        
        double sumatoria = 0;
        double termino=0;
        
        if(this.coordenadas==null)
            return -1;
        
        for(Punto punto:this.coordenadas)
        {
            termino = (punto.getX()-promedioX)*(punto.getY()-promedioY);
            sumatoria+=termino;
        }
        return sumatoria;
    }
    
    private double calcularDiferenciaDeXAlCuadrado(double promedioX)
    {
        if(this.coordenadas == null)
            return -1;
        
        double sumatoria = 0;
        double termino = 0;
        
        for(Punto punto:this.coordenadas)
        {
            termino = punto.getX()-promedioX;
            termino*=termino;
            sumatoria+=termino;
        }
        
        return sumatoria;
    }
    
    private double calcularB1(double promedioX,double promedioY)
    {
 
        double b1 = 0;
        double numerador = this.calcularSumatoriaDeDiferencias(promedioX,promedioY);
        double denominador = this.calcularDiferenciaDeXAlCuadrado(promedioX);
        b1 = numerador/denominador;
        
        return b1;
    }
    
    private double calcularB0(double promedioX,double promedioY,double b1)
    {
        return promedioY-(b1*promedioX);
    }
    private void calcularParametrosB()
    {
        double promedioX = this.calcularPromedioDeX();
        double promedioY = this.calcularPromedioDeY();
        
        this.b1 = this.calcularB1(promedioX, promedioY);
        this.b0 = this.calcularB0(promedioX, promedioY,b1);
    }
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmSimulador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmSimulador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmSimulador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmSimulador.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmSimulador().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration//GEN-END:variables
}
